<template>
  <div class="container">
    <el-row v-hasPerm="['index/show/charts']">
      <el-col :span="24">
        <el-form ref="queryFormRef" label-width="auto" :inline="true" :model="queryParam" class="demo-form-inline">
          <el-form-item label="平台" prop="platformId">
            <el-select clearable @keyup.enter="handleQuery" v-model="queryParam.platformId" placeholder="请选择" style="width: 14rem">
              <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="渠道" prop="channelId">
            <el-select clearable @keyup.enter="handleQuery" v-model="queryParam.channelId" placeholder="请选择" style="width: 14rem">
              <el-option v-for="item in MychannelArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车型" prop="vehicleTypeId">
            <el-select clearable @keyup.enter="handleQuery" v-model="queryParam.vehicleTypeId" placeholder="请选择" style="width: 14rem">
              <el-option v-for="item in MycarTypeArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市" prop="cityIds">
            <el-select filterable clearable multiple @keyup.enter="handleQuery" v-model="queryParam.cityIds" placeholder="请选择" style="width: 14rem">
              <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select @change="handleSelectType" clearable @keyup.enter="handleQuery" v-model="queryParam.type" placeholder="请选择" style="width: 14rem">
              <el-option label="年" :value="1"></el-option>
              <el-option label="月" :value="2"></el-option>
              <el-option label="日" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期类型" prop="dateType">
            <el-select clearable @keyup.enter="handleQuery" v-model="queryParam.dateType" placeholder="请选择" style="width: 14rem">
              <el-option label="用车时间" :value="1"></el-option>
              <el-option label="创建时间" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期" style="width: 18.4rem" v-if="queryParam.type == 1">
            <el-date-picker @change="handleDateChange" value-format="YYYY-01-01" v-model="dates" type="yearrange" placeholder="请选择" clearable />
          </el-form-item>
          <el-form-item label="日期" style="width: 18.4rem" v-if="queryParam.type == 2">
            <el-date-picker @change="handleDateChange" value-format="YYYY-MM-DD" v-model="dates" type="monthrange" placeholder="请选择" clearable />
          </el-form-item>
          <el-form-item label="日期" style="width: 18.4rem" v-if="queryParam.type == 3">
            <el-date-picker @change="handleDateChange" value-format="YYYY-MM-DD" v-model="dates" type="daterange" placeholder="请选择" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row class="charts">
      <el-col class="box" :span="24" v-for="(item, index) in countFormData" :key="index" v-loading="loading">
        <div class="header_case">
          <div class="item">
            <div class="title">城市</div>
            <div class="text">{{ item.cityName }}</div>
          </div>
          <div class="item">
            <div class="title">进单量</div>
            <div class="text">{{ item.totalNum }}</div>
          </div>
          <div class="item">
            <div class="title">完单量</div>
            <div class="text">{{ item.finishNum }}</div>
          </div>
          <div class="item">
            <div class="title">完单率</div>
            <div class="text">{{ item.finishRate }}%</div>
          </div>
          <div class="item">
            <div class="title">总流水</div>
            <div class="text">{{ item.totalFund }}</div>
          </div>
          <div class="item">
            <div class="title">毛利润</div>
            <div class="text">{{ item.gbFund }}</div>
          </div>
          <div class="item">
            <div class="title">利润率</div>
            <div class="text">{{ item.gbFundRate }}%</div>
          </div>
        </div>
        <el-scrollbar>
          <div class="scrollbar-flex-content">
            <div v-if="item.config1.domId" class="scrollbar-demo-item" :id="'chart1' + index" style="height: 400px; width: 31%"></div>
            <div v-if="item.config2.domId" class="scrollbar-demo-item" :id="'chart2' + index" style="height: 400px; width: 31%"></div>
            <div v-if="item.config3.domId" class="scrollbar-demo-item" :id="'chart3' + index" style="height: 400px; width: 31%"></div>
          </div>
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from "echarts";
import { channelArr, platFormArr, carTypeArr } from "@/enums/common";
import { reactive, ref, nextTick } from "vue";
import CommonApi from "@/api/common";

let queryParam = ref({
  platformId: 1,
  channelId: 0,
  vehicleTypeId: 0,
  cityIds: undefined,
  type: 3,
  startDate: "",
  endDate: "",
  dateType: 1,
});
const cityOptions = ref();
const MychannelArr = ref();
const MycarTypeArr = ref();
const dates = ref();
const countFormData: any = ref();
const queryFormRef = ref(ElForm);
const loading = ref();

// 重置查询
function handleResetQuery() {
  getDateRange();
  queryFormRef.value.resetFields();
  handleQuery();
}

//选择类型
const handleSelectType = () => {
  dates.value = "";
};
function handleDateChange(time: any) {
  if (time) {
    queryParam.value.startDate = `${time[0]}`;
    queryParam.value.endDate = `${time[1]}`;
  } else {
    queryParam.value.startDate = "";
    queryParam.value.endDate = "";
  }
}
const handleQuery = () => {
  CommonApi.getEchartsCityInfo(queryParam.value).then((data: any) => {
    if (data.code == 0) {
      countFormData.value = data.result;
      countFormData.value = countFormData.value.map((item: any, index: any) => {
        return {
          ...item,
          config1: {
            domId: "chart1" + index,
            keys: ["totalNum", "finishNum", "finishRate"],
            legend: ["进单量", "完单量", "完单率"],
            dataList: item.dateList,
            title: "单量",
          },
          config2: {
            domId: "chart2" + index,
            keys: "gbFund",
            dataList: item.dateList,
            title: "利润",
          },
          config3: {
            domId: "chart3" + index,
            keys: "gbFundRate",
            dataList: item.dateList,
            title: "利润率",
          },
        };
      });
      // 使用 nextTick 确保 DOM 更新完成
      nextTick(() => {
        countFormData.value.forEach((item: any) => {
          setCharts({
            domId: item.config1.domId,
            keys: item.config1.keys,
            legend: item.config1.legend,
            dataList: item.dateList,
            title: item.config1.title,
          });
          setChart(item.config2.domId, item.config2.title, item.config2.keys, item.dateList);
          setChart(item.config3.domId, item.config3.title, item.config3.keys, item.dateList);
        });
      });
    }
  });
};

function setChart(domId: any, title: string, key: any, list: any) {
  let date: any = [];
  let values: any = [];
  list.forEach((item: any) => {
    date.push(item.date);
    values.push(item[key]);
  });

  var myChart = echarts.init(document.getElementById(domId));

  // 绘制图表
  myChart.setOption({
    title: {
      text: title,
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: [title],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {},
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: date,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: title,
        type: "line",
        data: values,
        label: {
          show: true,
          position: "top", // 标签显示的位置，可以是'top'、'inside'、'left'、'right'等
          formatter: "{c}", // 标签内容格式，{c}表示数据值
          color: "black", // 标签文字颜色
          fontSize: 12, // 标签文字大小
        },
      },
    ],
  });
}
function setCharts(config: { domId: string; keys: string[]; legend: string[]; dataList: any[]; title: string }) {
  const { domId, keys, legend, dataList, title } = config;
  let date: any = [];
  let seriesData: any = {}; // 使用一个对象来存储不同系列的数据
  dataList.forEach((item: any) => {
    date.push(item.date);
    keys.forEach((key, index) => {
      const legendName = legend[index];
      if (!seriesData[key]) {
        seriesData[key] = []; // 如果该系列的数据数组不存在，则初始化它
      }
      seriesData[key].push(item[key] || 0); // 如果item中没有该key，则默认添加0
    });
  });
  // 根据seriesData来配置ECharts的series
  // 根据seriesData来配置ECharts的series
  const series = keys.map((key, index) => ({
    name: legend[index], // 使用legend数组中的值作为name
    type: "line",
    data: seriesData[key].map((value: any, index: any) => ({
      value,
      label: {
        show: true,
        position: "top", // 标签显示的位置，可以是'top'、'inside'、'left'、'right'等
        formatter: "{c}", // 标签内容格式，{c}表示数据值
        color: "black", // 标签文字颜色
        fontSize: 12, // 标签文字大小
      },
    })),
  }));
  console.log(";DOMIDDOMDIDODMID", domId);

  var myChart = echarts.init(document.getElementById(domId));
  // 绘制图表
  myChart.setOption({
    title: {
      text: title,
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: legend,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {},
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: date,
    },
    yAxis: {
      type: "value",
    },
    series: series,
  });
}

// 创建一个全局的 loading 实例
// 创建一个全局的 loading 实例
onMounted(() => {
  loading.value = true;
  getDateRange();
  MychannelArr.value = JSON.parse(JSON.stringify(channelArr));
  MychannelArr.value.unshift({ label: "全部", value: 0 });
  MycarTypeArr.value = JSON.parse(JSON.stringify(carTypeArr));
  MycarTypeArr.value.unshift({ label: "全部", value: 0 });
  CommonApi.getCity({ pageNo: 1, pageSize: 9999 }).then((data: any) => {
    if (data.code == 0) {
      cityOptions.value = data.result;
      cityOptions.value.unshift({ name: "全部", id: 0 });
    }
  });

  CommonApi.getEchartsCityInfo(queryParam.value).then((data: any) => {
    if (data.code == 0) {
      countFormData.value = data.result;
      countFormData.value = countFormData.value.map((item: any, index: any) => {
        return {
          ...item,
          config1: {
            domId: "chart1" + index,
            keys: ["totalNum", "finishNum", "finishRate"],
            legend: ["进单量", "完单量", "完单率"],
            dataList: item.dateList,
            title: "单量",
          },
          config2: {
            domId: "chart2" + index,
            keys: "gbFund",
            dataList: item.dateList,
            title: "利润",
          },
          config3: {
            domId: "chart3" + index,
            keys: "gbFundRate",
            dataList: item.dateList,
            title: "利润率",
          },
        };
      });
      nextTick(() => {
        loading.value = false;

        countFormData.value.forEach((item: any) => {
          setCharts({
            domId: item.config1.domId,
            keys: item.config1.keys,
            legend: item.config1.legend,
            dataList: item.dateList,
            title: item.config1.title,
          });
          setChart(item.config2.domId, item.config2.title, item.config2.keys, item.dateList);
          setChart(item.config3.domId, item.config3.title, item.config3.keys, item.dateList);
        });
      });
    }
  });
});
const getDateRange = () => {
  const today = new Date();
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(today.getDate() - 7);
  const start = sevenDaysAgo.toISOString().split("T")[0];
  const end = today.toISOString().split("T")[0];
  dates.value = [start, end];
  queryParam.value.startDate = start;
  queryParam.value.endDate = end;
};
</script>
<style lang="scss" scoped>
:deep(.el-scrollbar__bar) {
  bottom: 64px !important;
}
.container {
  width: 100vw !important;
  padding: 24px;
}
.charts {
  width: 87vw;
  .box {
    padding: 14px;
    background: #fff;
    // margin-left: 14px;
    text-align: center;
    margin-top: 14px;
    .header_case {
      display: flex;
      justify-content: space-around;
      text-align: center;
      margin-top: 14px;
      margin-bottom: 14px;
      .item {
        .title {
          font-size: 20px;
          font-weight: bold;
        }
        .text {
          margin-top: 4px;
          font-size: 18px;
          color: #e81830;
        }
      }
    }
    .bottom_case {
      margin-top: 20px;
      display: flex;
      justify-content: space-around;
      .item {
        text-align: center;
        font-size: 14px;
        line-height: 2;
        .text {
          color: #4b82e9;
        }
      }
    }
  }
}
.scrollbar-flex-content {
  display: flex;
}
.scrollbar-demo-item {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  color: var(--el-color-danger);
}
</style>


